#include <stdint.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>

#include "py/compile.h"
#include "py/runtime.h"
#include "py/repl.h"
#include "py/gc.h"
#include "py/mperrno.h"
#include "shared/runtime/pyexec.h"

#include "mod/machine.h"
//#include "crypto/wm_crypto_hard.h"

#include "lib/littlefs/lfs1.h"
#include "lib/littlefs/lfs1_util.h"
#include "lib/littlefs/lfs2.h"
#include "lib/littlefs/lfs2_util.h"

#include "extmod/vfs.h"
#include "extmod/vfs_fat.h"
#include "extmod/vfs_lfs.h"

#include "storage.h"
#include "FreeRTOS.h"


#if MICROPY_ENABLE_COMPILER
void do_str(const char *src, mp_parse_input_kind_t input_kind) {
    nlr_buf_t nlr;
    if (nlr_push(&nlr) == 0) {
        mp_lexer_t *lex = mp_lexer_new_from_str_len(MP_QSTR__lt_stdin_gt_, src, strlen(src), 0);
        qstr source_name = lex->source_name;
        mp_parse_tree_t parse_tree = mp_parse(lex, input_kind);
        mp_obj_t module_fun = mp_compile(&parse_tree, source_name, true);
        mp_call_function_0(module_fun);
        nlr_pop();
    } else {
        // uncaught exception
        mp_obj_print_exception(&mp_plat_print, (mp_obj_t)nlr.ret_val);
    }
}
#endif

static char *stack_top;
#if MICROPY_ENABLE_GC
static char heap[MICROPY_HEAP_SIZE];
#endif

#if MICROPY_HW_REPL_UART
STATIC pyb_uart_obj_t pyb_uart_repl_obj;
STATIC uint8_t pyb_uart_repl_rxcache[UART_FIFO_FULL];
STATIC uint8_t pyb_uart_repl_rxbuf[MICROPY_HW_UART_REPL_RXBUF];
#endif

STATIC machine_rtc_obj_t machine_rtc_obj;  // rtc module object


//
// 声明全局函数
//
extern int factory_reset_create_filesystem(mp_obj_type_t *vfs, mp_obj_t bdev);


// 硬件初始化(静态资源)
static void xt804_hw_init(void)
{
    HAL_Init();
    SystemClock_Config(MICROPY_HW_FREQ);
    
    //tls_crypto_init();               // 初始化加解密模块(使能中断)
#if MICROPY_HW_DIS_SWJ
    __HAL_AFIO_REMAP_SWJ_DISABLE;    // 禁止jtag接口
#endif

#if MICROPY_HW_EN_CACHE
    MP_HW_CACHE_INIT();              // 使能cache(只对读加速, W801启动读写加速会炸(群大佬说的)) 
#endif

#if MICROPY_HW_REPL_UART             // 添加REPL关联的调试串口
    pyb_uart_repl_obj.base.type = &pyb_uart_type;
    pyb_uart_repl_obj.uart_id = MICROPY_HW_UART_REPL;
    pyb_uart_repl_obj.timeout = 50;
    // huart
    pyb_uart_repl_obj.huart.Instance = _get_uart_by_id(MICROPY_HW_UART_REPL);
	pyb_uart_repl_obj.huart.Init.BaudRate = 115200;
	pyb_uart_repl_obj.huart.Init.WordLength = UART_WORDLENGTH_8B;
	pyb_uart_repl_obj.huart.Init.StopBits = UART_STOPBITS_1;
	pyb_uart_repl_obj.huart.Init.Parity = UART_PARITY_NONE;
	pyb_uart_repl_obj.huart.Init.Mode = UART_MODE_TX | UART_MODE_RX;
	pyb_uart_repl_obj.huart.Init.HwFlowCtl = UART_HWCONTROL_NONE;
    // 初始化串口模块
    HAL_UART_Init(&pyb_uart_repl_obj.huart);
    
    pyb_uart_repl_obj.is_enabled = true;
    
    pyb_uart_repl_obj.fifo.buf = pyb_uart_repl_rxbuf;
    pyb_uart_repl_obj.fifo.buf_len = sizeof(pyb_uart_repl_rxbuf);
    pyb_uart_repl_obj.fifo.front = 0;
    pyb_uart_repl_obj.fifo.rear = 0;
   
    MP_STATE_PORT(pyb_uart_obj_all)[MICROPY_HW_UART_REPL] = &pyb_uart_repl_obj;
    MP_STATE_PORT(pyb_stdio_uart) = &pyb_uart_repl_obj;
    
    HAL_UART_Receive_IT(&pyb_uart_repl_obj.huart, pyb_uart_repl_rxcache, 0);  // 调用一次即可, 以后从队列里拿数据
#endif
    // rtc module(utime module rely on rtc module)
    machine_rtc_obj.base.type = &machine_rtc_type;
    MP_STATE_PORT(rtc_obj) = &machine_rtc_obj;
    
    machine_rtc_obj.hpmu.Instance = PMU;
    machine_rtc_obj.hpmu.ClkSource = PMU_CLKSOURCE_32RC;
    HAL_PMU_Init(&machine_rtc_obj.hpmu);
    
    machine_rtc_obj.time.Year = MICROPY_HW_RTC_YEAR;
    machine_rtc_obj.time.Month = MICROPY_HW_RTC_MONTH;
    machine_rtc_obj.time.Date = MICROPY_HW_RTC_DAY;
    machine_rtc_obj.time.Hours = MICROPY_HW_RTC_HOUR;
    machine_rtc_obj.time.Minutes = MICROPY_HW_RTC_MINUTE;
    machine_rtc_obj.time.Seconds = MICROPY_HW_RTC_SECOND;
    machine_rtc_obj.timezone = MICROPY_HW_RTC_TIMEZONE;
    HAL_PMU_RTC_Start(&machine_rtc_obj.hpmu, &machine_rtc_obj.time);
}


STATIC int vfs_mount_and_chdir(mp_obj_t bdev, mp_obj_t mount_point) {
    nlr_buf_t nlr;
    mp_int_t ret = -MP_EIO;
    if (nlr_push(&nlr) == 0) {
        mp_obj_t args[] = { bdev, mount_point };
        mp_vfs_mount(2, args, (mp_map_t*)&mp_const_empty_map);
        mp_vfs_chdir(mount_point);
        ret = 0; // success
        nlr_pop();
    } else {
        mp_obj_base_t *exc = nlr.ret_val;
        if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(exc->type), MP_OBJ_FROM_PTR(&mp_type_OSError))) {
            mp_obj_t v = mp_obj_exception_get_value(MP_OBJ_FROM_PTR(exc));
            mp_obj_get_int_maybe(v, &ret); // get errno value
            ret = -ret;
        }
    }
    return ret;
}


MP_NOINLINE STATIC bool init_flash_fs(void) {
    
    // Default block device to entire flash storage
    mp_obj_t bdev = MP_OBJ_FROM_PTR(&flash_obj);
    const mp_obj_type_t *vfs = MP_OBJ_NULL;
    
    //printf("%s:%d start.\n", __func__, __LINE__);
    #if MICROPY_VFS_LFS1 || MICROPY_VFS_LFS2
    // Try to detect the block device used for the main filesystem, based on the first block
    uint8_t buf[256];
    storage_read(buf, MICROPY_HW_BLK_START, sizeof(buf));
    mp_int_t len = -1;

    #if MICROPY_VFS_LFS1
    if (memcmp(&buf[40], "littlefs", 8) == 0) {
        // LFS1
        lfs1_superblock_t *superblock = (void*)&buf[12];
        uint32_t block_size = lfs1_fromle32(superblock->d.block_size);
        uint32_t block_count = lfs1_fromle32(superblock->d.block_count);
        len = block_count * block_size;
    }
    vfs = &mp_type_vfs_lfs1;
    #endif

    #if MICROPY_VFS_LFS2
    if (memcmp(&buf[8], "littlefs", 8) == 0) {
        // LFS2
        lfs2_superblock_t *superblock = (void*)&buf[20];
        uint32_t block_size = lfs2_fromle32(superblock->block_size);
        uint32_t block_count = lfs2_fromle32(superblock->block_count);
        len = block_count * block_size;
    }
    vfs = &mp_type_vfs_lfs2;
    #endif

    if (len != -1) {
        // Detected a littlefs filesystem so create correct block device for it
        mp_obj_t args[] = { MP_OBJ_NEW_QSTR(MP_QSTR_blk_offs), MP_OBJ_NEW_SMALL_INT(MICROPY_HW_FS_BLK_OFFS),  
                            MP_OBJ_NEW_QSTR(MP_QSTR_blk_cnt), MP_OBJ_NEW_SMALL_INT(FLASH_PART1_BLK_CNT),
                          };
        bdev = flash_type.make_new(&flash_type, 0, 2, args);
        //printf("%s:%d make bdev.\n", __func__, __LINE__);
    }
    #endif
    // Try to mount the flash on "/flash" and chdir to it for the boot-up directory.
    mp_obj_t mount_point = MP_OBJ_NEW_QSTR(MP_QSTR__slash_flash);
    int ret = vfs_mount_and_chdir(bdev, mount_point);
    
    //printf("init_flash_fs() mount stat:%d.\n", ret);
    if (ret == -MP_ENODEV && bdev == MP_OBJ_FROM_PTR(&flash_obj)) {
        // No filesystem, bdev is still the default (so didn't detect a possibly corrupt littlefs),
        // and didn't already create a filesystem, so try to create a fresh one now.
        ret = factory_reset_create_filesystem((mp_obj_type_t*)vfs, bdev);
        //printf("%s:%d mount stat:%d.\n", __func__, __LINE__, ret);
        
        if (ret == 0) {
            ret = vfs_mount_and_chdir(bdev, mount_point);
            //printf("%s:%d mount stat:%d.\n", __func__, __LINE__, ret);
        }
    }
    
    if (ret != 0) {
        printf("MPY: can't mount flash\n");
        return false;
    }

    return true;
}


void mpy_task(void *args) {

    // 这里进行硬件初始化
    xt804_hw_init();
    
    // 在这里添加初始化代码
    // todo here.

    int stack_dummy;
    
soft_reset:
    stack_top = (char *)&stack_dummy;

    // Stack limit should be less than real stack size, so we have a chance
    // to recover from limit hit.  (Limit is measured in bytes.)
    // Note: stack control relies on main thread being initialised above
    #if MICROPY_STACK_CHECK
    mp_stack_set_top(&_estack);
    mp_stack_set_limit((char *)&_estack - (char *)&_sstack - 1024);
    #endif

    
    #if MICROPY_ENABLE_GC
    gc_init(heap, heap + sizeof(heap));
    #endif
    
    #if MICROPY_ENABLE_PYSTACK
    static mp_obj_t pystack[384];
    mp_pystack_init(pystack, &pystack[384]);
    #endif
    
    mp_init();
    
    mp_obj_list_init(MP_OBJ_TO_PTR(mp_sys_path), 0);
    mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR_)); // current dir (or base dir of the script)
    mp_obj_list_init(MP_OBJ_TO_PTR(mp_sys_argv), 0);

    
    // Initialise the local flash filesystem.
    // Create it if needed, mount in on /flash, and set it as current dir.
    bool mounted_flash = false;
    #if MICROPY_HW_ENABLE_STORAGE
    mounted_flash = init_flash_fs();
    #endif
    if (mounted_flash) {
        mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR__slash_flash));               // /flash
        mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR__slash_flash_slash_lib));     // /flash/lib
    }
 
    // reset config variables; they should be set by boot.py
    MP_STATE_PORT(pyb_config_main) = MP_OBJ_NULL;
    

    // run boot-up scripts
    //pyexec_frozen_module("_boot.py");
    pyexec_file_if_exists("boot.py");
    if (pyexec_mode_kind == PYEXEC_MODE_FRIENDLY_REPL) {
        int ret = pyexec_file_if_exists("main.py");
        if (ret & PYEXEC_FORCED_EXIT) {
            goto soft_reset_exit;
        }
    }

    #if MICROPY_ENABLE_COMPILER
    // copy from stm32
    // Main script is finished, so now go into REPL mode.
    // The REPL mode can change, or it can request a soft reset.
    for (;;) {
        if (pyexec_mode_kind == PYEXEC_MODE_RAW_REPL) {
            if (pyexec_raw_repl() != 0) {
                break;
            }
        } else {
            if (pyexec_friendly_repl() != 0) {
                break;
            }
        }
    }
    // do_str("print('hello world!', list(x+1 for x in range(10)), end='eol\\n')", MP_PARSE_SINGLE_INPUT);
    // do_str("for i in range(10):\r\n  print(i)", MP_PARSE_FILE_INPUT);
    #else
    //pyexec_frozen_module("frozentest.py");
    #endif
    
soft_reset_exit:
    mp_deinit();
    
    goto soft_reset;
}

#if MICROPY_ENABLE_GC
void gc_collect(void) {
    // WARNING: This gc_collect implementation doesn't try to get root
    // pointers from CPU registers, and thus may function incorrectly.
    void *dummy;
    gc_collect_start();
    gc_collect_root(&dummy, ((mp_uint_t)stack_top - (mp_uint_t)&dummy) / sizeof(mp_uint_t));
    gc_collect_end();
    //gc_dump_info();
}
#endif

#if 0
   /* 使用vfs + littlefs2, 通过宏定义到特定接口即可 */
// There is no filesystem so opening a file raises an exception.
mp_lexer_t *mp_lexer_new_from_file(const char *filename) {
    mp_raise_OSError(MP_ENOENT);
}

// There is no filesystem so stat'ing returns nothing.
mp_import_stat_t mp_import_stat(const char *path) {
    return MP_IMPORT_STAT_NO_EXIST;
}

mp_obj_t mp_builtin_open(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs) {
    return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_open_obj, 1, mp_builtin_open);
#endif


void nlr_jump_fail(void *val) {
    while (1) {
        ;
    }
}

void NORETURN __fatal_error(const char *msg) {
    while (1) {
        ;
    }
}

#ifndef NDEBUG
void MP_WEAK __assert_func(const char *file, int line, const char *func, const char *expr) {
    printf("Assertion '%s' failed, at file %s:%d\n", expr, file, line);
    __fatal_error("Assertion failed");
}
#endif
